package net.wicp.tams.common.spring.autoconfig.constant;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.StringUtil;

@Slf4j
public enum SpringConf {

	consul("consul:", 1),

	apollo("ApolloBootstrapPropertySources:", 2),

	configserver("configService:", 3),

	bootstrap("applicationConfig: [classpath:/bootstrap-", 4),

	application("applicationConfig: [classpath:/application-", 5),

	system("systemProperties", 99), // 系统变量

	env("systemEnvironment", 100); // 环境变量

	static {
		SpringConf[] values = SpringConf.values();
		for (SpringConf value : values) {
			String convertClass = Conf.get("common.spring.autoconfig.convert." + value.name());
			if (StringUtil.isNotNull(convertClass)) {
				try {
					IConvert convert = (IConvert) Class.forName(convertClass).newInstance();
					value.setConvert(convert);
				} catch (Exception e) {
					log.error(convertClass + "转换器创建错误", e);
				}
			}
		}
	}

	private SpringConf(String keyPre, int order) {
		this.keyPre = keyPre;
		this.order = order;
	}

	private final String keyPre;
	private int order;
	private IConvert convert;

	public void setConvert(IConvert convert) {
		this.convert = convert;
	}

	private final Map<String, LinkedHashMap<String, String>> props = new HashMap<>();// 这里面不区分大小写

	public int getOrder() {
		return order;
	}

	public void setOrder(int order) {
		this.order = order;
	}

	public String getKeyPre() {
		return keyPre;
	}

	public Map<String, LinkedHashMap<String, String>> getProps() {
		return props;
	}

	/**
	 * 把得到的属性做转换
	 * 
	 * @param filekey 属性文件的key
	 * @param allMap  传入的所有属性
	 * @return
	 */
	public Map<String, String> getPropsConvert(String filekey, Map<String, String> allMap) {
		return convert == null ? this.props.get(filekey)
				: this.convert.convertMap(filekey, this.props.get(filekey), allMap);
	}

	/**
	 * 得到优先级的倒序
	 * 
	 * @return
	 */
	public static SpringConf[] sortDesc() {
		SpringConf[] values = SpringConf.values();
		Arrays.sort(values, new Comparator<SpringConf>() {
			@Override
			public int compare(SpringConf o1, SpringConf o2) {
				return o2.getOrder() - o1.getOrder();
			}
		});
		return values;
	}

}
